import React, { PureComponent } from 'react';
import { Spin, Menu, Icon, Avatar, Tooltip, Dropdown, Button, Modal } from 'antd';
import moment from 'moment';
import { routerRedux } from 'dva/router';
import { reloadAuthorized } from '../../utils/Authorized';
import { modalWidth } from '../../../config';
import NoticeIcon from '../NoticeIcon';
import styles from './index.less';
import tools from '../../utils';

export default class GlobalHeaderRight extends PureComponent {
  state = {
    name: tools.funcGetLocalValue('name') || '管理员',
    headPortrait:
      tools.funcGetLocalValue('headPortrait') || tools.funcUrl('/static/BiazfanxmamNRoxxVxka.png'),
    notifyCount: tools.funcGetLocalValue('notifyCount') || 0,
    pwd_visible: false,
    pwd_loading: true,
    api_visible: false,
    api_loading: true,
    doc_visible: false,
    doc_loading: true,
    notice_visible: false,
    notice_title: '',
    notice_text: '',
    popupVisible: false,
  };

  getNoticeData() {
    const { notices = [] } = this.props;
    if (notices.length === 0) {
      return [];
    }
    const newNotices = notices.map(notice => {
      const newNotice = { ...notice };
      newNotice.datetime = moment(notice.atTime).fromNow();
      return newNotice;
    });
    return newNotices;
  }

  // 页眉右边小菜单的点击事件
  funcOnMenuClick = item => {
    const { props } = this;
    switch (item.key) {
      // 更改密码
      case 'pwd':
        if (tools.funcIsIE()) props.dispatch(routerRedux.push('/editPw'));
        else this.setState({ pwd_visible: true });
        break;

      // 测试接口
      case 'api':
        if (tools.funcIsIE()) props.dispatch(routerRedux.push('/basic/resource'));
        else this.setState({ api_visible: true });
        break;

      // 退出登录
      default:
        tools.funcSetLocalValue('antd-pro-authority', 'guest');
        reloadAuthorized();
        props.dispatch(routerRedux.push('/user/login'));
    }
  };

  // 把获取到的文章正文填写到编辑器中
  funcFillText = () => {
    const { state } = this;
    const dom = document.getElementById('div_text');
    if (dom) dom.innerHTML = state.notice_text;
    else setTimeout(this.funcFillText, 100);
  };

  render() {
    const { fetchingNotices, onNoticeVisibleChange, onNoticeClear, theme, dispatch } = this.props;

    let incApi = <Menu.Divider />;
    const userName = tools.funcGetLocalValue('userName');
    if (userName === 'admin') {
      // 只有大管理员才能进行"测试接口"
      incApi = [
        <Menu.Divider key="line0" />,
        <Menu.Item key="api">
          <Icon type="api" />
          测试接口
        </Menu.Item>,
        <Menu.Divider key="line1" />,
      ];
    }
    const menu = (
      <Menu className={styles.menu} selectedKeys={[]} onClick={this.funcOnMenuClick}>
        <Menu.Item key="pwd">
          <Icon type="key" />
          更改密码
        </Menu.Item>
        {incApi}
        <Menu.Item key="logout">
          <Icon type="logout" />
          退出登录
        </Menu.Item>
      </Menu>
    );

    const noticeData = this.getNoticeData();
    let className = styles.right;
    if (theme === 'dark') {
      className = `${styles.right}  ${styles.dark}`;
    }

    const { state } = this;

    return (
      <div className={className}>
        <Tooltip title="首页">
          <a
            className={styles.action}
            onClick={() => {
              dispatch(routerRedux.push('/basic/index'));
            }}
          >
            <Icon type="home" className={styles.icon} />
          </a>
        </Tooltip>
        <Tooltip title="使用文档">
          <a
            className={styles.action}
            onClick={() => {
              this.setState({ doc_visible: true });
            }}
          >
            <Icon type="question-circle-o" className={styles.icon} />
          </a>
        </Tooltip>
        <NoticeIcon
          className={styles.action}
          count={state.notifyCount}
          onItemClick={item => {
            this.state.notice_text = item.description;
            this.setState({
              notice_visible: true,
              notice_title: item.title,
              popupVisible: false,
            });
            this.funcFillText();
          }}
          onClear={onNoticeClear}
          onPopupVisibleChange={() => {
            this.setState({ popupVisible: !state.popupVisible });
            onNoticeVisibleChange(!state.popupVisible);
          }}
          onViewMore={() => {
            this.setState({ popupVisible: false });
            dispatch(routerRedux.push('/basic/notice'));
          }}
          popupVisible={state.popupVisible}
          loading={fetchingNotices}
          popupAlign={{ offset: [20, -16] }}
        >
          <NoticeIcon.Tab
            list={noticeData}
            showClear={false}
            emptyText="暂无新通知"
            emptyImage={tools.funcUrl('/static/wAhyIChODzsoKIOBHcBk.svg')}
          />
        </NoticeIcon>
        <Dropdown overlay={menu}>
          <span className={`${styles.action} ${styles.account}`}>
            <Avatar size="small" className={styles.avatar} src={state.headPortrait} />
            <span className={styles.name}>{state.name}</span>
          </span>
        </Dropdown>
        <Modal
          width={modalWidth}
          title={
            <div>
              <Icon type="question-circle-o" style={{ fontSize: 18 }} />
              <span> 使用文档</span>
            </div>
          }
          visible={state.doc_visible}
          footer={[
            <a
              key="pdf"
              id="a_pdf"
              href={tools.funcUrl('/static/readme.pdf')}
              download="readme.pdf"
            >
              &nbsp;
            </a>,
            <Button
              key="open"
              type="primary"
              onClick={() => {
                this.setState({ doc_visible: false });
                window.open(tools.funcUrl('/static/readme.pdf'));
              }}
            >
              {tools.funcDlgBtnSave('打开', 'folder-open', 16)}
            </Button>,
            <Button
              key="download"
              onClick={() => {
                const a = document.getElementById('a_pdf');
                a.click();
              }}
            >
              {tools.funcDlgBtnSave('下载', 'download', 16)}
            </Button>,
            <Button
              key="close"
              onClick={() => {
                this.setState({ doc_visible: false });
              }}
            >
              {tools.funcDlgBtnCancel('关闭')}
            </Button>,
          ]}
          onCancel={() => {
            this.setState({ doc_visible: false });
          }}
        >
          <Spin spinning={state.doc_loading}>
            <div style={{ margin: -24 }}>
              <iframe
                src={tools.funcUrl('/static/readme.htm')}
                width="100%"
                height="502"
                name="iframe_readme"
                frameBorder="0"
                title=" "
                onLoad={() => {
                  this.setState({ doc_loading: false });
                }}
              />
            </div>
          </Spin>
        </Modal>
        <Modal
          width={640}
          title={
            <div>
              <Icon type="key" style={{ fontSize: 18 }} />
              <span> 更改密码</span>
            </div>
          }
          visible={state.pwd_visible}
          footer={null}
          onCancel={() => {
            this.setState({ pwd_visible: false });
            document.all.iframe_modifyPassword.contentDocument.location.reload();
          }}
        >
          <Spin spinning={state.pwd_loading}>
            <iframe
              src={tools.funcUrlDynamic('/blank/modifyPassword')}
              width="100%"
              height="230"
              name="iframe_modifyPassword"
              frameBorder="0"
              scrolling="no"
              title=" "
              onLoad={() => {
                this.setState({ pwd_loading: false });
              }}
            />
          </Spin>
        </Modal>
        <Modal
          width={modalWidth}
          title={
            <div>
              <Icon type="api" style={{ fontSize: 18 }} />
              <span> 测试接口</span>
            </div>
          }
          visible={state.api_visible}
          footer={null}
          onCancel={() => {
            this.setState({ api_visible: false });
          }}
        >
          <Spin spinning={state.api_loading}>
            <iframe
              src={tools.funcUrlDynamic('/blank/resWin')}
              width="100%"
              height="600"
              frameBorder="0"
              scrolling="no"
              style={{ margin: '-24px 0' }}
              title=" "
              onLoad={() => {
                this.setState({ api_loading: false });
              }}
            />
          </Spin>
        </Modal>
        <Modal
          width={640}
          title={
            <div>
              <Icon type="file-text" style={{ fontSize: 18 }} />
              <span> {state.notice_title}</span>
            </div>
          }
          visible={state.notice_visible}
          footer={
            <Button
              key="close"
              onClick={() => {
                this.setState({ notice_visible: false });
              }}
            >
              {tools.funcDlgBtnCancel('关闭')}
            </Button>
          }
          onCancel={() => {
            this.setState({ notice_visible: false });
          }}
        >
          <div id="div_text" />
        </Modal>
      </div>
    );
  }
}
